const { execSync } = require("child_process");
const root = execSync("npm root -g").toString().trim();
module.paths.push(root);
// const jsonServer = require(`${root}/json-server`);
const jsonServer = require(`json-server`); // 必须 0.17.4, 否则最新版会报错找不到全局 module, 源代码的 bug
const path = require("path");
const apiServer = jsonServer.create();

apiServer.use(
  jsonServer.rewriter({
    "/api/admin/sigin": "/signin",
    "/api/admin/weekly": "/weekly",
  })
);

const router = jsonServer.router(path.join(process.cwd(), "db.json5"));
const middlewares = jsonServer.defaults();

apiServer.use(middlewares); // logger, static cors no-cache
apiServer.use(jsonServer.bodyParser);
apiServer.use((req, res, next) => {
  res
    .setHeader("Content-Type", "application/json")
    .setHeader("MaxAge", "123")
    .setHeader("MaxAge", "456");
  next();
});

apiServer.get("/api/admin/signin", (req, res) => {
  res.cookie("uuid", Math.random(), { signed: false, httpOnly: false });
  res.cookie("uuidv2", Math.random(), { signed: false, httpOnly: false });
  res.end(JSON.stringify({ code: 200, msg: "oook" }));
});
apiServer.get("/api/admin/weekly", (req, res) => {
  res.json(res.body);
});

apiServer.use(router);
apiServer.listen(3000, () => {
  console.log("JSON Server is running: http://localhost:3000");
});
